<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\PatientTypeRequest;
use App\Services\Api\ApiService;
use App\Services\PatientTypeService;
use App\Http\Controllers\Controller;

class PatientTypeController extends Controller
{

    private $service;

    public function __construct(ApiService $apiService,PatientTypeService $service)
    {
        parent::__construct($apiService);
        $this->service = $service;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $showPage = $this->getShowPage();
        if (!empty(request()->input('showpage'))) $showPage = request()->input('showpage');
        $this->service->repository->pushCriteria(app('Prettus\Repository\Criteria\RequestCriteria'));
        $patientTypes = $this->service->repository->scopeQuery(function ($query){
            return $query->with('deportment');
        })->paginate($showPage);
        return $this->apiService->run(200, $patientTypes);
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(PatientTypeRequest $request)
    {
        try{
            $patientType = $this->service->repository->create($request->all());
            return $this->apiService->run(200, $patientType);
        }catch (\Exception $exception){
            return $this->apiService->run(500);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $patientType = $this->service->repository->scopeQuery(function ($query){
            return $query->with('deportment');
        })->find($id);
       // if (empty($patientType)) return $this->apiService->run(400);
        return $this->apiService->run(200, $patientType);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(PatientTypeRequest $request, $id)
    {
        try {
            $patientType = $this->service->repository->find($id)->update($request->all());
            if (empty($patientType)) return $this->apiService->run(400);
            return $this->apiService->run(200);
        }catch (\Exception $exception){
            return $this->apiService->run(500);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $patientType = $this->service->repository->destroy($id);
        if (empty($patientType)) return $this->apiService->run(400);
        return $this->apiService->run(200);
    }
}
